package com.service.scheduling.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.service.dao.enums.CommonStatusEnums;
import com.service.dao.enums.MqMsgVo;
import com.service.dao.enums.SysMqTopicEnum;
import com.service.dao.mapper.SysMqRecordMapper;
import com.service.dao.model.SysMqRecord;
import com.service.scheduling.service.SysMqRecordService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service("sysMqRecordService")
public class SysMqRecordServiceImpl extends ServiceImpl<SysMqRecordMapper, SysMqRecord> implements SysMqRecordService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveMqMsgRecord(SysMqTopicEnum topic, MqMsgVo mqMsgVo) {

        SysMqRecord record = SysMqRecord.builder()
                .mqTopic(topic.getName())
                .sendTime(new Date())
                .sendData(JSON.toJSONString(mqMsgVo))
                .recordStatus(CommonStatusEnums.INVALID.getCode())
                .build();
        save(record);

        mqMsgVo.setMsgId(record.getRecordId());
    }

    @Override
    public List<SysMqRecord> listNotReceiveMqMsg(SysMqTopicEnum topic) {
        Date queryData = DateUtils.addMinutes(new Date(), -2);
        return list(new LambdaQueryWrapper<SysMqRecord>()
                .eq(SysMqRecord::getRecordStatus, CommonStatusEnums.INVALID.getCode())
                .eq(SysMqRecord::getMqTopic, topic.getName())
                .le(SysMqRecord::getSendTime, queryData));
    }
}
